package com.caiheng.api.controller.estate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.dao.examine.ExamineApproveTemplateUserMapper;
import com.caiheng.api.entity.attendance.AttendanceGroupUser;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.estate.EstateUser;
import com.caiheng.api.entity.examine.*;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.attendance.AttendanceGroupUserService;
import com.caiheng.api.service.estate.EstateUserService;
import com.caiheng.api.service.examine.*;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  OA 办公 审批流程
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/examine/approve")//url:模块/资源/{}/细分
public class ExamineApproveController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private ExamineApproveService approveService;
    @Resource
    private ExamineApproveRegRecordService approveRegRecordService;
    @Resource
    private ExamineApproveRegImgService approveRegImgService;
    @Resource
    private ExamineApproveRegInfoService approveRegInfoService;
    @Resource
    private ExamineApproveRegAdminRecordService approveRegAdminRecordService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private AttendanceGroupUserService attendanceGroupUserService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    @Value("${web.imgPrefix}")
    private String imgPrefix;

    @Resource
    private LockTemplate lockTemplate;
    @Resource
    private ExamineApproveTemplateUserService approveTemplateUserService;


    /**
     *  类目列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
//            List<ExamineApproveRegRecord> recordList = approveRegRecordService.list();
//            for (ExamineApproveRegRecord record : recordList){
//                record.setApproveNo("E" + DateUtil.getSdfffTimes(record.getCreateTime()));
//                approveRegRecordService.updateById(record);
//            }

            ExamineApprove examineApprove = approveService.findById(82);
            ExamineApproveTemplateUser templateUser = approveTemplateUserService.findById(181);
            ExamineApproveRegRecord regRecord = approveRegRecordService.getById(828);
            ExamineApproveRegAdminRecord adminRecord = approveRegAdminRecordService.getById(2893);

            //给当前用户发送推送消息
            wxTemplateService.sendWxMsgExamineApproveToNext(examineApprove, templateUser, regRecord, adminRecord, 1);

        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }


    /**
     *  类目列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject approveList(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "examine/approve/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int approve_type = jsonRequest.containsKey("approve_type") ? jsonRequest.getInt("approve_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

//            AttendanceGroupUser groupUser = attendanceGroupUserService.getDefaultGroup(user);
//            if(groupUser == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定OA办公人员"),true,true);
//            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员"),true,true);
            }

            EstateUser estateUser = estateUserService.getEstateBySysUser(user.getSysUserId());

            QueryWrapper<ExamineApprove> qw = new QueryWrapper<>();
//            qw.eq("approve_type",approve_type);
            qw.eq("property_id", sysUser.getPropertyId());
            if(estateUser!= null){
                if(estateUser.getEstateId() > 0){
                    qw.eq("estate_id", estateUser.getEstateId());
                }
            }

            List<ExamineApprove> list = approveService.getPageEntityList(qw,pageIndex,pageSize);
            map.put("approves",list);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     * 添加审批
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/record")
    public JSONObject addRecord(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            logBefore(logger, "examine/approve/add/record 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int approve_id = jsonRequest.containsKey("approve_id") ? jsonRequest.getInt("approve_id") : 0;
            JSONObject reg_record = jsonRequest.containsKey("reg_record") ? jsonRequest.getJSONObject("reg_record") : null;
            JSONArray regInfos = jsonRequest.containsKey("reg_info") ? jsonRequest.getJSONArray("reg_info") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ExamineApprove approve = approveService.findById(approve_id);
            if(approve == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批类型不存在"),true,true);
            }

//            AttendanceGroupUser groupUser = attendanceGroupUserService.getDefaultGroup(user);
//            if(groupUser == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定OA办公人员"),true,true);
//            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员"),true,true);
            }

            ExamineApproveRegRecord regRecord = JSONUtil.toBean(reg_record, ExamineApproveRegRecord.class);
            if(regRecord != null){
                regRecord.setUserId(user.getId());
                regRecord.setApproveType(approve.getApproveType());
                int recordId = approveRegRecordService.addRecord(user,approve, regRecord,regInfos,sysUser);
                if(recordId > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "申请成功",recordId), true, false);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "申请失败"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "数据异常"), true, true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 修改审批
     * @param
     * @throws Exception
     */
    @PostMapping(value="/update/record")
    public JSONObject updateRecord(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            logBefore(logger, "examine/approve/add/record 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int approve_id = jsonRequest.containsKey("approve_id") ? jsonRequest.getInt("approve_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;
            JSONObject reg_record = jsonRequest.containsKey("reg_record") ? jsonRequest.getJSONObject("reg_record") : null;
            JSONArray regInfos = jsonRequest.containsKey("reg_info") ? jsonRequest.getJSONArray("reg_info") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ExamineApprove approve = approveService.findById(approve_id);
            if(approve == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批类型不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员"),true,true);
            }

            ExamineApproveRegRecord regRecord = JSONUtil.toBean(reg_record, ExamineApproveRegRecord.class);
            if(regRecord != null){
                regRecord.setUserId(user.getId());
                regRecord.setApproveType(approve.getApproveType());
                int recordId = approveRegRecordService.updateRecord(user,approve, regRecord,regInfos,sysUser);
                if(recordId > 0){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "申请成功",recordId), true, false);
                }else{
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "申请失败"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "数据异常"), true, true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     *  上报记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/record/list")
    public JSONObject orderList(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "examine/approve/record/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int type = jsonRequest.containsKey("type") ? jsonRequest.getInt("type") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员"),true,true);
            }


            List<ExamineApproveRegRecord> list = approveRegRecordService.getMyRegRecordListByState(user,state,pageIndex,pageSize);
            map.put("records",list);


            EstateUser estateUser = estateUserService.getEstateBySysUser(user.getSysUserId());

            QueryWrapper<ExamineApprove> qwApprove =new QueryWrapper<>();
            qwApprove.eq("state",1);
            qwApprove.eq("property_id",sysUser.getPropertyId());
            if(estateUser!= null){
                qwApprove.eq("estate_id",estateUser.getEstateId());
            }
            List<ExamineApprove> approveList = approveService.getPageEntityList(qwApprove,pageIndex,pageSize);
            map.put("approveList",approveList);

            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }


    /**
     *  管理员审批记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/admin/record/list")
    public JSONObject adminHandleList(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "examine/approve/record/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int type = jsonRequest.containsKey("type") ? jsonRequest.getInt("type") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;
            int is_copy = jsonRequest.containsKey("is_copy") ? jsonRequest.getInt("is_copy") : 0;
            String searchValue = jsonRequest.containsKey("searchValue") ? jsonRequest.getStr("searchValue") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }


            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员"),true,true);
            }

            //抄送
            List<ExamineApproveRegRecord> list = new ArrayList<>();
            if(state == 3){
                list = approveRegRecordService.getAdminCopyListByState(user,state, searchValue, pageIndex,pageSize);
                map.put("records",list);
            }else{
                list = approveRegRecordService.getAdminHandleListByState(user,state, searchValue, pageIndex,pageSize);
                map.put("records",list);
            }

//            EstateUser estateUser = estateUserService.getEstateBySysUser(user.getSysUserId());

//            QueryWrapper<ExamineApprove> qwApprove =new QueryWrapper<>();
//            qwApprove.eq("state",1);
//            qwApprove.eq("property_id",sysUser.getPropertyId());
//            if(estateUser!= null){
//                qwApprove.eq("estate_id",estateUser.getEstateId());
//            }
//            List<ExamineApprove> approveList = approveService.getPageEntityList(qwApprove,pageIndex,pageSize);
//            map.put("approveList",approveList);

            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }


    /**
     *  记录详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/record/detail")
    public JSONObject orderDetail(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            logBefore(logger, "examine/approve/record/detail 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int record_id = jsonRequest.containsKey("record_id") ? jsonRequest.getInt("record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ExamineApproveRegRecord record = approveRegRecordService.getDetail(user_id, record_id);

            map.put("record",record);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }


    /**
     *   领导审批记录（同意/拒绝）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/handle/record")
    public JSONObject addAdminRecord(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;

        if(StrUtil.isEmpty(requestParam)){
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
        }

        logBefore(logger, "examine/approve/handle/record 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
        JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

        int admin_record_id = jsonRequest.containsKey("admin_record_id") ? jsonRequest.getInt("admin_record_id") : 0;

        int approve_record_id = jsonRequest.containsKey("approve_record_id") ? jsonRequest.getInt("approve_record_id") : 0;
        LockInfo lockInfo = lockTemplate.lock(admin_record_id + "_handleRecord", 30000L, 5000L, RedissonLockExecutor.class);
        if (lockInfo == null) {
            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"业务处理中,请稍后再试"),true,true);
        }

        try{
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : "";
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ExamineApproveRegRecord regRecord = approveRegRecordService.findById(approve_record_id);
            if(regRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批记录不存在"),true,true);
            }

            if(regRecord.getState() == 3){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批已撤销"),true,true);
            }

            if(regRecord.getState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批已完成"),true,true);
            }

            ExamineApproveRegAdminRecord adminRecord = approveRegAdminRecordService.findById(admin_record_id);
            if(adminRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请求数据有异常，请联系管理员"),true,true);
            }

            if(adminRecord.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前不属于您的审核流程"),true,true);
            }

            //审批的状态 审批状态  0 - 未处理  1 - 审批同意  2 - 审批拒绝
            adminRecord.setState(state);
            adminRecord.setContent(content);

            int ret = approveRegAdminRecordService.handleRecord(user,regRecord,adminRecord);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"处理失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }finally {
            //释放锁
            lockTemplate.releaseLock(lockInfo);
        }
        return result;
    }


    /**
     *   撤销审批
     * @param
     * @throws Exception
     */
    @PostMapping(value="/cancel/record")
    public JSONObject cancelRecord(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            logBefore(logger, "examine/approve/handle/record 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int approve_record_id = jsonRequest.containsKey("approve_record_id") ? jsonRequest.getInt("approve_record_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ExamineApproveRegRecord regRecord = approveRegRecordService.findById(approve_record_id);
            if(regRecord == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批记录不存在"),true,true);
            }
            if(regRecord.getUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批不属于你"),true,true);
            }

            if(regRecord.getState() == 3){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批已撤销"),true,true);
            }

            if(regRecord.getState() == 2){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该审批已完成"),true,true);
            }

            int ret = approveRegRecordService.cancelRecord(user,regRecord);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"处理成功"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"处理失败"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImgRepair(@RequestParam("record_id") int record_id,@RequestParam("sort") int sort,  HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            ExamineApproveRegRecord record = approveRegRecordService.getById(record_id);
            if(record == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该记录不存在"), true, true);
            }
            boolean bl = false;
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certUrl = maps.get(key);
                        if (!certUrl.isEmpty()) {
                            String prefix = certUrl.getOriginalFilename().substring(certUrl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "examine_approve_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certUrl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_EXAMINE_APPROVE;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certUrl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        ExamineApproveRegImg regImg = new ExamineApproveRegImg();
                                        regImg.setApproveRecordId(record_id);
                                        regImg.setImgType(0);
                                        regImg.setImgUrl(img_key);
                                        regImg.setSort(sort);
                                        bl = approveRegImgService.save(regImg);
//                                        record.setImgUrl(img_key);
//                                        bl = warmHeartCashRecordService.updateById(record);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }

            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "图片上传失败"), true, true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

}
